package com.ruoyi.matrix.service.impl;

import cn.hutool.json.JSONObject;
import com.ruoyi.matrix.service.NotifyType;
import com.ruoyi.matrix.service.WeComService;
import com.ruoyi.common.utils.DateUtils;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Service
public class WeComServiceImpl implements WeComService {
    private final String prefix = "[Hunbter.tips]:\n";
    private final String devUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ca04546c-d6a3-414d-ab71-b9c2fda0fa70";
    private final String prodUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=e7317f05-ba59-4cc9-8c45-de35dbbbfbf5";
    private final Logger logger = LoggerFactory.getLogger(WeComServiceImpl.class);
    private final OkHttpClient client = new OkHttpClient.Builder().build();

    @Override
    public void send(@NotNull String message, @NotNull String mode) {
        // machine
        String host = "unknown";
        String ip = "127.0.0.1";
        try {
            InetAddress ia = InetAddress.getLocalHost();
            host = ia.getHostName();//获取计算机主机名
            ip = ia.getHostAddress();//获取计算机IP
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


        String str = prefix
                + DateUtils.format(new Date()) + "\n"
                + "From " + host + "@" + ip + " Reported:\n"
                + message;

        if (str != null && str.length() > 1500) {
            str = str.substring(0, 1500);
        }

        str = str.replace("`", ";");

        JSONObject object = new JSONObject();
        JSONObject content = new JSONObject();
        content.set("content", str);
        object.set("msgtype", "markdown");
        object.set("markdown", content);
        String payload = object.toString();

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), payload);
        if(mode.equals(NotifyType.dev) || mode.equals(NotifyType.both)) {
            Request devRequest = new Request.Builder().url(devUrl).post(body).build();
            try(Response _r1 =  client.newCall(devRequest).execute()) {
            } catch (Exception e) {
                this.logger.error("发送消息失败: $message", e);
            }
        }

        if(mode.equals(NotifyType.prod) || mode.equals(NotifyType.both)) {
            Request prodRequest = new Request.Builder().url(prodUrl).post(body).build();
            try(Response _r2 =  client.newCall(prodRequest).execute()) {
            } catch (Exception e) {
                this.logger.error("发送消息失败: $message", e);
            }
        }
    }
}
